package com.qianfeng.controller;

import com.github.pagehelper.PageInfo;
import com.qianfeng.model.Dept;
import com.qianfeng.service.DeptService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;

@Controller
@RequestMapping("/dept")
public class DeptController {

    @Autowired
    private DeptService deptService;

    //在控制层方法中，如果前端的条件传到，直接以参数的方式接收，那么条件可以在URL后面进行拼接传入
    @RequestMapping("/findPage")
    public String findPage(Model model, Dept param, Integer page, Integer rows) {
        //如果前端不传分页条件，则后台给个默认值
        if (page == null) {
            page = 1;
        }
        if (rows == null) {
            rows = 3;
        }
        PageInfo<Dept> pageInfo = deptService.findPage(param, page, rows);
        model.addAttribute("pageInfo", pageInfo);
        //将查询的条件再带回页面
        model.addAttribute("param", param);

        return "dept-list";
    }

    @RequestMapping("/save")
    public String save(Dept dept) {
        deptService.save(dept);
        return "redirect:/dept/findPage";//重定向
    }

    @RequestMapping("/delById")
    @ResponseBody
    public HashMap delById(Integer id) {
        boolean result = deptService.delById(id);
        HashMap map = new HashMap();
        if (result) {
            map.put("success", true);
            map.put("message", "操作成功");
        } else {
            map.put("success", false);
            map.put("message", "操作失败");
        }
        return map;
    }
}
